package com.example.demo8;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class GameController {
    private Player player;
    private EnemySystem enemySystem;
    private CollisionSystem collisionSystem;
    private List<Projectile> projectiles;
    private boolean gameOver;
    private boolean gameWin;
    private int score;
    private int level;
    private int[][] room;
    private Map map;
    private List<Hero> selectedHeroes;

    public GameController(boolean twoPlayerMode, List<Hero> selectedHeroes, Map map) {
        this.map = map;
        this.selectedHeroes = selectedHeroes; // 存储选择的英雄
        this.player = new Player(800, 500, 100, 4, 100, 10); // 设置玩家起始位置
        this.enemySystem = new EnemySystem();
        this.projectiles = new ArrayList<>();
        this.score = 0;
        this.level = 1;
        this.gameOver = false;
        this.gameWin = false;

        // 初始化障碍物
        room = new int[RPGgame.WIDTH / RPGgame.TILE_SIZE][RPGgame.HEIGHT / RPGgame.TILE_SIZE];
        generateRoom();

        // 创建碰撞系统
        collisionSystem = new CollisionSystem(map.getCurrentMap(), RPGgame.TILE_SIZE);

        // 初始化敌人
        enemySystem.spawnEnemies(5, new java.awt.Point((int) player.getX(), (int) player.getY()), new java.awt.Rectangle(0, 0, RPGgame.WIDTH, RPGgame.HEIGHT));
    }

    private void generateRoom() {
        Random random = new Random();
        for (int x = 0; x < room.length; x++) {
            for (int y = 0; y < room[0].length; y++) {
                room[x][y] = (x == 0 || x == room.length - 1 || y == 0 || y == room[0].length - 1) ? 1 : 0;
            }
        }

        // 随机生成障碍物
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(room.length - 4) + 2;
            int y = random.nextInt(room[0].length - 4) + 2;
            room[x][y] = 1;
        }
    }

    public void update() {
        if (gameOver || gameWin) return;

        // 更新碰撞系统的地图布局
        collisionSystem.updateRoom(map.getCurrentMap());

        player.update(projectiles, collisionSystem);  // 更新玩家
        updateEnemies();  // 更新敌人
        updateProjectiles();  // 更新子弹

        if (enemySystem.getEnemies().isEmpty()) {
            if (++level > 3) {
                gameWin = true;
            } else {
                map.nextMap(); // 切换到下一个地图
                enemySystem.spawnEnemies(5 + level * 2, new java.awt.Point((int) player.getX(), (int) player.getY()), new java.awt.Rectangle(0, 0, RPGgame.WIDTH, RPGgame.HEIGHT));
                player.setHealth(player.getMaxHealth());  // 恢复玩家生命
            }
        }
    }

    private void updateEnemies() {
        enemySystem.updateAll(player.getX(), player.getY(), collisionSystem, projectiles);
        enemySystem.getEnemies().forEach(enemy -> {
            if (collisionSystem.checkEntityCollision(player.getX(), player.getY(), RPGgame.PLAYER_SIZE / 2, enemy.x, enemy.y, Enemy.ENEMY_SIZE / 2) && !player.isInvincible()) {
                player.setHealth(player.getHealth() - enemy.damage);
                player.setInvincible(true);
                player.setInvincibleTimer(60);
                if (player.getHealth() <= 0) {
                    gameOver = true;
                }
            }
        });
    }

    private void updateProjectiles() {
        projectiles.removeIf(proj -> {
            proj.update();

            if (proj.x < 0 || proj.x > RPGgame.WIDTH || proj.y < 0 || proj.y > RPGgame.HEIGHT) {
                return true;
            }

            if (collisionSystem.checkWallCollision(proj.x, proj.y, RPGgame.PROJECTILE_SIZE / 2)) {
                return true;
            }

            if (proj.isEnemyProjectile) {
                if (collisionSystem.checkEntityCollision(proj.x, proj.y, RPGgame.PROJECTILE_SIZE / 2, player.getX(), player.getY(), RPGgame.PLAYER_SIZE / 2)) {
                    player.setHealth(player.getHealth() - proj.damage);
                    return true;
                }
            } else {
                boolean hitEnemy = false;
                List<Enemy> enemiesToRemove = new ArrayList<>();

                for (Enemy enemy : enemySystem.getEnemies()) {
                    if (collisionSystem.checkEntityCollision(proj.x, proj.y, RPGgame.PROJECTILE_SIZE / 2, enemy.x, enemy.y, Enemy.ENEMY_SIZE / 2)) {
                        enemy.health -= proj.damage;
                        score += 100;
                        hitEnemy = true;

                        if (enemy.health <= 0) {
                            enemiesToRemove.add(enemy);
                        }
                        break;
                    }
                }

                enemySystem.getEnemies().removeAll(enemiesToRemove);

                if (hitEnemy) {
                    return true;
                }
            }

            return false;
        });
    }

    public boolean isGameOver() {
        return gameOver;
    }

    public boolean isGameWin() {
        return gameWin;
    }

    public void handleInput(KeyCode keyCode, boolean isPressed) {
        switch (keyCode) {
            case W -> player.handleInput(KeyCode.W, isPressed);
            case S -> player.handleInput(KeyCode.S, isPressed);
            case A -> player.handleInput(KeyCode.A, isPressed);
            case D -> player.handleInput(KeyCode.D, isPressed);
            case SPACE -> player.handleInput(KeyCode.SPACE, isPressed);
        }
    }

    public void render(GraphicsContext gc) {
        player.render(gc, RPGgame.PLAYER_SIZE);
        enemySystem.getEnemies().forEach(enemy -> enemy.draw(gc));
        projectiles.forEach(proj -> proj.draw(gc));

        // 绘制障碍物
        int[][] room = map.getCurrentMap();
        for (int x = 0; x < room.length; x++) {
            for (int y = 0; y < room[0].length; y++) {
                if (room[x][y] == 1) {
                    gc.setFill(Color.GRAY);  // 灰色的障碍物
                    gc.fillRect(x * RPGgame.TILE_SIZE, y * RPGgame.TILE_SIZE, RPGgame.TILE_SIZE, RPGgame.TILE_SIZE);
                }
            }
        }

        drawUI(gc);

        if (gameOver) {
            drawCenteredText(gc, "游戏结束", Color.RED, 48);
            drawCenteredText(gc, "按 R 键重新开始", Color.WHITE, 24);
        }

        if (gameWin) {
            drawCenteredText(gc, "胜利!", Color.GOLD, 48);
            drawCenteredText(gc, "按 R 键重新开始", Color.WHITE, 24);
        }
    }

    private void drawCenteredText(GraphicsContext gc, String text, Color color, double fontSize) {
        gc.setFill(Color.rgb(0, 0, 0, 0.7));
        gc.fillRect(0, 0, RPGgame.WIDTH, RPGgame.HEIGHT);
        gc.setFill(color);
        gc.setFont(javafx.scene.text.Font.font(fontSize));
        gc.fillText(text, RPGgame.WIDTH / 2 - 100, RPGgame.HEIGHT / 2 - 50);
    }

    private void drawUI(GraphicsContext gc) {
        double barWidth = 200, barHeight = 20;
        double healthBarWidth = barWidth * ((double) player.getHealth() / player.getMaxHealth());

        gc.setFill(Color.GRAY);
        gc.fillRect(20, 20, barWidth, barHeight);

        gc.setFill(Color.RED);
        gc.fillRect(20, 20, healthBarWidth, barHeight);

        gc.setStroke(Color.WHITE);
        gc.strokeRect(20, 20, barWidth, barHeight);

        gc.setFill(Color.WHITE);
        gc.setFont(javafx.scene.text.Font.font(16));
        gc.fillText("生命值: " + player.getHealth() + "/" + player.getMaxHealth(), 25, 35);
        gc.fillText("分数: " + score, 20, 65);
        gc.fillText("关卡: " + level, 20, 90);
        gc.fillText("当前伤害" + player.getDamage(), 20, 115);

        gc.setFill(Color.YELLOW);
        gc.fillText("按B进入商店", 20, 140);
    }
}